package com.xlh.wjdcserver.config;

import com.xlh.wjdcserver.interceptor.JwtTokenInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.*;

@Configuration
@Slf4j
public class WebMvcConfiguration implements WebMvcConfigurer {

    @Autowired
    private JwtTokenInterceptor jwtTokenInterceptor;

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("http://localhost:81", "http://192.168.0.195:81")//前端地址
                .allowCredentials(true)
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowedHeaders("*");
    }

    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(jwtTokenInterceptor)
                .excludePathPatterns(
                        "/user/login",
                        "/v3/api-docs/**",              // ✅ 排除 OpenAPI 文档路径
                        "/swagger-ui.html",             // ✅ 排除 Swagger UI 页面
                        "/swagger-ui/**",               // ✅ 静态资源
                        "/doc.html",                    // ✅ 若使用 knife4j（可选）
                        "/webjars/**",                   // ✅ Swagger 依赖的静态资源
                        "/captcha/**",
                        "/question/listQuestionsByQid/**",
                        "/WriteAnswer/**",
                        "/user/qlogin",
                        "/answer/addAnswer/**"
                );
    }

    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        // 只转发 /WriteAnswer/xxx 这类路径，让 Vue Router 接管
        registry.addViewController("/WriteAnswer/{id:[^\\.]+}")
                .setViewName("forward:/index.html");
    }

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/avatar/**")
                .addResourceLocations("file:D:\\avatar\\");
    }
}
